package cn.kawa.basic.util;

import cn.kawa.basic.jwt.JwtUtils;
import cn.kawa.basic.jwt.LoginData;
import cn.kawa.basic.jwt.Payload;
import cn.kawa.basic.jwt.RsaUtils;
import cn.kawa.user.domain.LoginInfo;

import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;

public class LoginContext {
    /**
     * 从request里 获取并返回当前的登陆人信息，
     * @param request
     * @return LoginInfo   ：
     */
    public static LoginInfo getLoginUser(HttpServletRequest request){
        //从请求头获取token - JWT
        String token = request.getHeader("token");
        if(token!=null){
            try {
                //获取公钥
                PublicKey publicKey = RsaUtils.getPublicKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
                //解析JWT转成LoginData[loginInfo(),permission ,menu]
                Payload<LoginData> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginData.class);
                //返回登录人信息
                return payload.getLoginData().getLoginInfo();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}
